package com.radiodhamal.app;

import static com.radiodhamal.app.constant.GlobalConfig.isPlaying;
import static com.radiodhamal.app.constant.GlobalConfig.isRecording;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.radiodhamal.app.constant.GlobalConfig;
import com.radiodhamal.app.object.MyObject;
import com.radiodhamal.app.prefrence.SaveSettings;

public class MainActivity extends MyApp implements OnClickListener {

	private Button playButton = null;
	private Button recordButton = null;
	private Button btnRV = null;
	private Button btnSR = null;
	private Button btnWeb1 = null;
	private Button btnWeb2 = null;
	private Button btnFace = null;
	private Button btnTweet = null;
	private Button btnYoutu = null;
	private Button btnMail = null;
	private Button btnRequest = null;
	private SeekBar volumeControl = null;
	private LinearLayout llquangcao;
	private ImageView logo = null;

	private Button saveSongsButton = null;
	MediaPlayer mp = new MediaPlayer();
	// boolean isRecording = false;
	long totalsec = 0;
	private long totalKbRead = 0;
	private File downloadingMediaFile;
	File savemydownloadFileDir;
	File savemydownloadFile;
	static int counter = 0;
	String filename = "";
	Context context = MainActivity.this;
	private AudioManager audioManager = null;
	SaveSettings savesettings;

	private AdView adView; // Quảng cáo

	private MyObject objVirsa;
	private MyObject objSangat;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);
		GlobalConfig.channel = 1;

		// Khởi tạo các Object
		objVirsa = new MyObject(GlobalConfig.idLogoVirsa,
				GlobalConfig.idImgRequestVirsa, GlobalConfig.web_radiovirsa,
				GlobalConfig.addr_fb_radiovirsa,
				GlobalConfig.addr_tw_radiovirsa,
				GlobalConfig.addr_youtu_radiovirsa,
				GlobalConfig.addr_mail_radiovirsa, GlobalConfig.addr_request);

		objSangat = new MyObject(GlobalConfig.idLogoSangat,
				GlobalConfig.idImgRequestSangat, GlobalConfig.web_kokariweb,
				GlobalConfig.addr_fb_sikh, GlobalConfig.addr_tw_sikh,
				GlobalConfig.addr_youtu_sikh, GlobalConfig.addr_mail_sikh,
				GlobalConfig.addr_request);

		savesettings = new SaveSettings(context);
		initViews();
		initControls();
	}

	private void initViews() {
		playButton = (Button) findViewById(R.id.btnPlay);
		recordButton = (Button) findViewById(R.id.btnRecord);
		btnRV = (Button) findViewById(R.id.btnRV);
		btnSR = (Button) findViewById(R.id.btnSR);
		btnWeb1 = (Button) findViewById(R.id.btnWeb1);
		btnWeb2 = (Button) findViewById(R.id.btnWeb2);
		btnFace = (Button) findViewById(R.id.btnFacebook);
		btnTweet = (Button) findViewById(R.id.btnTweet);
		btnYoutu = (Button) findViewById(R.id.btnYoutube);
		btnMail = (Button) findViewById(R.id.btnMail);
		btnRequest = (Button) findViewById(R.id.btnRequest);
		logo = (ImageView) findViewById(R.id.logo);
		logo.setImageResource(R.drawable.logo_radiovirsa_big);

		llquangcao = (LinearLayout) findViewById(R.id.quangcao);
		adView = new AdView(this, AdSize.BANNER, GlobalConfig.idQuangcao);
		llquangcao.addView(adView);
		adView.loadAd(new AdRequest());

		playButton.setOnClickListener(this);
		recordButton.setOnClickListener(this);
		btnSR.setOnClickListener(this);
		btnRV.setOnClickListener(this);
		btnWeb1.setOnClickListener(this);
		btnWeb2.setOnClickListener(this);
		btnFace.setOnClickListener(this);
		btnTweet.setOnClickListener(this);
		btnYoutu.setOnClickListener(this);
		btnMail.setOnClickListener(this);
		btnRequest.setOnClickListener(this);
	}

	public void stopRecord() {
		isRecording = false;
		recordButton.setBackgroundResource(R.drawable.recording);
	}

	public void recordRadio() {
		if (isPlaying) { // Nếu như đang chơi nhạc
			if (isRecording == false) {
				recordButton.setBackgroundResource(R.drawable.recording_on);
				isRecording = true;
				new SaveMusicAsyncTask().execute();
			} else {
				stopRecord();
			}
		} else {
			recordButton.setBackgroundResource(R.drawable.recording);
			Toast.makeText(context, "Please play the radio first",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void stopRadio() {
		isPlaying = false;
		savesettings.setRadioPlaying(isPlaying);
		playButton.setBackgroundResource(R.drawable.play);
		if (isMyServiceRunning()) {
			stopService(new Intent(context,
					com.radiodhamal.app.service.ManageRadio.class));
		}
	}

	public void playRadio() {
		if (isPlaying == false) {
			playButton.setBackgroundResource(R.drawable.pause);
			try {
				isPlaying = true;
				savesettings.setRadioPlaying(isPlaying);
				startService(new Intent(MainActivity.this,
						com.radiodhamal.app.service.ManageRadio.class));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			stopRadio();
		}
	}

	public class SaveMusicAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			try {
				downloadAudioIncrement();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO Auto-generated method stub
			return null;
		}

		public void downloadAudioIncrement() throws IOException {

			URLConnection cn = new URL(GlobalConfig.radiolinks_stream_virsa)
					.openConnection();
			cn.connect();
			InputStream stream = cn.getInputStream();
			if (stream == null) {
				Log.e(getClass().getName(),
						"Unable to create InputStream for mediaUrl:"
								+ GlobalConfig.radiolinks_stream_virsa);
			}
			downloadingMediaFile = new File(context.getCacheDir(),
					"downloadingMedia_" + (counter++) + ".mp3");
			FileOutputStream out = new FileOutputStream(downloadingMediaFile);
			byte buf[] = new byte[16384];
			int totalBytesRead = 0, incrementalBytesRead = 0;
			do {
				int numread = stream.read(buf);
				if (numread <= 0)
					break;
				out.write(buf, 0, numread);
				totalBytesRead += numread;
				incrementalBytesRead += numread;
				totalKbRead = totalBytesRead / 1000;
			} while (isRecording);
			stream.close();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// Toast.makeText(MainActivity.this,
			// "saved at " + savemydownloadFile.getPath(),
			// Toast.LENGTH_SHORT).show();
			afterrecordSaveDialog();

			// playRecordedSong();
		}

	}

	public void moveFile(File oldLocation, File newLocation) throws IOException {

		if (oldLocation.exists()) {
			BufferedInputStream reader = new BufferedInputStream(
					new FileInputStream(oldLocation));
			BufferedOutputStream writer = new BufferedOutputStream(
					new FileOutputStream(newLocation, false));
			try {
				byte[] buff = new byte[8192];
				int numChars;
				while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
					writer.write(buff, 0, numChars);
				}
			} catch (IOException ex) {
				throw new IOException("IOException when transferring "
						+ oldLocation.getPath() + " to "
						+ newLocation.getPath());
			} finally {
				try {
					if (reader != null) {
						writer.close();
						reader.close();
					}
				} catch (IOException ex) {
					Log.e(getClass().getName(),
							"Error closing files when transferring "
									+ oldLocation.getPath() + " to "
									+ newLocation.getPath());
				}
			}
		} else {
			throw new IOException(
					"Old location does not exist when transferring "
							+ oldLocation.getPath() + " to "
							+ newLocation.getPath());
		}

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(context)
				.create();

		// Setting Dialog Title
		alertDialog.setTitle("Radio Virsa!");

		// Setting Dialog Message
		alertDialog.setMessage("Do You Want To ");

		// Setting Icon to Dialog
		alertDialog.setIcon(android.R.drawable.ic_dialog_alert);

		// Setting OK Button
		alertDialog.setButton("Quit", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
				if (isPlaying)
					stopService(new Intent(context,
							com.radiodhamal.app.service.ManageRadio.class));
				finish();
			}
		});
		alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();

			}
		});
		alertDialog.show();
	}

	public void playRecordedSong() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(context)
				.create();

		// Setting Dialog Title
		alertDialog.setTitle("Recorded Song");

		// Setting Dialog Message
		alertDialog.setMessage("Your Song is saved.\n Listen Now!!");

		// Setting Icon to Dialog
		// alertDialog.setIcon(R.drawable.record_dialog);

		// Setting OK Button
		alertDialog.setButton("Play", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// Write your code here to execute after dialog closed
				Intent intent = new Intent();
				intent.setAction(android.content.Intent.ACTION_VIEW);
				// File file = new File(savemydownloadFile);
				intent.setDataAndType(Uri.fromFile(savemydownloadFile),
						"audio/*");
				startActivity(intent);

			}
		});
		alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnRV:
			clickVirsaButton();
			break;

		case R.id.btnSR:
			clickSangatButton();
			break;

		case R.id.btnPlay:
			playRadio();
			break;

		case R.id.btnRecord:
			recordRadio();
			break;

		case R.id.btnWeb1:
			Intent myWebLink1 = new Intent(android.content.Intent.ACTION_VIEW);
			myWebLink1.setData(Uri.parse(objVirsa.getURLWeb()));
			startActivity(myWebLink1);
			break;

		case R.id.btnWeb2:
			Intent myWebLink2 = new Intent(android.content.Intent.ACTION_VIEW);
			myWebLink2.setData(Uri.parse(objSangat.getURLWeb()));
			startActivity(myWebLink2);
			break;

		case R.id.btnFacebook:
			Intent linkface = new Intent(android.content.Intent.ACTION_VIEW);
			if (GlobalConfig.channel == 1)
				linkface.setData(Uri.parse(objVirsa.getAddrFacebook()));
			else if (GlobalConfig.channel == 2)
				linkface.setData(Uri.parse(objVirsa.getAddrFacebook()));
			startActivity(linkface);
			break;

		case R.id.btnTweet:
			Intent linktweet = new Intent(android.content.Intent.ACTION_VIEW);
			if (GlobalConfig.channel == 1)
				linktweet.setData(Uri.parse(objVirsa.getAddrTwitter()));
			else if (GlobalConfig.channel == 2)
				linktweet.setData(Uri.parse(objVirsa.getAddrTwitter()));
			startActivity(linktweet);
			break;

		case R.id.btnYoutube:
			Intent linkyoutu = new Intent(android.content.Intent.ACTION_VIEW);
			if (GlobalConfig.channel == 1)
				linkyoutu.setData(Uri.parse(objVirsa.getAddrYoutube()));
			else if (GlobalConfig.channel == 2)
				linkyoutu.setData(Uri.parse(objVirsa.getAddrYoutube()));
			startActivity(linkyoutu);
			break;

		case R.id.btnMail:
			Intent sendIntent;
			sendIntent = new Intent(Intent.ACTION_SEND);
			sendIntent.setType("message/rfc822");

			if (GlobalConfig.channel == 1)
				sendIntent.putExtra(Intent.EXTRA_EMAIL,
						new String[] { objVirsa.getAddrMail() });
			else if (GlobalConfig.channel == 2)
				sendIntent.putExtra(Intent.EXTRA_EMAIL,
						new String[] { objSangat.getAddrMail() });

			sendIntent.putExtra(Intent.EXTRA_SUBJECT, "");
			sendIntent.putExtra(Intent.EXTRA_TEXT, "");
			startActivity(Intent.createChooser(sendIntent, "Send Mail"));
			break;

		case R.id.btnRequest:
			Intent linkRequest = new Intent(android.content.Intent.ACTION_VIEW);
			linkRequest.setData(Uri.parse(GlobalConfig.addr_request));
			startActivity(linkRequest);
			break;

		default:
			break;
		}
	}

	private void initControls() {
		try {
			volumeControl = (SeekBar) findViewById(R.id.volume_control);
			audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			volumeControl.setMax(audioManager
					.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
			volumeControl.setProgress(audioManager
					.getStreamVolume(AudioManager.STREAM_MUSIC));

			volumeControl
					.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
						@Override
						public void onStopTrackingTouch(SeekBar arg0) {
						}

						@Override
						public void onStartTrackingTouch(SeekBar arg0) {
						}

						@Override
						public void onProgressChanged(SeekBar arg0,
								int progress, boolean arg2) {
							audioManager.setStreamVolume(
									AudioManager.STREAM_MUSIC, progress, 0);

						}
					});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean isMyServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if ("com.radiodhamal.app.service.ManageRadio"
					.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	void afterrecordSaveDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Save File");
		builder.setMessage("Enter your File Name:");

		// Use an EditText view to get user input.
		final EditText input = new EditText(this);
		input.setId(0);
		builder.setView(input);

		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				String songname = input.getText().toString();
				// Log.d(TAG, "User name: " + value);
				try {
					// create a File object for the parent directory
					savemydownloadFileDir = new File("/sdcard/RadioDhamal/");
					// have the object build the directory structure, if needed.
					savemydownloadFileDir.mkdirs();
					// create a File object for the output file
					savemydownloadFile = new File(android.os.Environment
							.getExternalStorageDirectory() + "/RadioDhamal/",
							songname + ".mp3");
					moveFile(downloadingMediaFile, savemydownloadFile);
					Toast.makeText(context, "Your Song is Saved",
							Toast.LENGTH_SHORT).show();

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return;
			}
		});

		builder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(context, "Your Song is Discarded!!!",
								Toast.LENGTH_SHORT).show();
						return;
					}
				});

		builder.create();
		builder.show();
	}

	private void clickVirsaButton() {
		// Đk if này để nhấn button 1 lần. Nếu nhấn button đó tiếp tục thì cũng
		// không được xét tới nữa
		if (GlobalConfig.channel != 1) {
			GlobalConfig.channel = 1;
			logo.setImageResource(objVirsa.getIdLogo());
			btnRequest.setBackgroundResource(objVirsa.getIdBtnRequest());
			stopRadio();
			stopRecord();
			Log.d("A0", "vao Virsa");
		}
	}

	private void clickSangatButton() {
		// Đk if này để nhấn button 1 lần. Nếu nhấn button đó tiếp tục thì cũng
		// không được xét tới nữa
		if (GlobalConfig.channel != 2) {
			GlobalConfig.channel = 2;
			logo.setImageResource(objSangat.getIdLogo());
			btnRequest.setBackgroundResource(objSangat.getIdBtnRequest());
			stopRadio();
			stopRecord();
			Log.d("A0", "vao Sangat");
		}
	}
}